package com.nova.android.tvlauncher.ui.view

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.HomeBannerAtvDto
import com.nova.android.tvlauncher.ui.view.ad.AdManagerImpl
import com_github_lib_base.currentActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

class ImageCarouselView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    val viewPager: ViewPager2
    private var autoScrollJob: Job? = null
    private var autoScrollInterval = 2*60*1000L
    private var imageList: List<HomeBannerAtvDto> = emptyList()
    private var previousView: ImageView? = null

    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.carousel_layout, this, true)
        viewPager = rootView.findViewById(R.id.viewPager)
        configureViewPager()
    }

    private var onPageSelectedListener: ((position: Int) -> Unit)? = null
    fun onPageSelected(listener: (position: Int) -> Unit) {
        onPageSelectedListener = listener
    }

    private fun configureViewPager() {
        layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        viewPager.offscreenPageLimit = 1
        viewPager.setPageTransformer(null) // 取消系统滑动动画
        viewPager.isUserInputEnabled = false // 禁止手动滑动

        // 添加页面切换回调，做 alpha 动画
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val recyclerView = viewPager.getChildAt(0) as? RecyclerView
                val holder =
                    recyclerView?.findViewHolderForAdapterPosition(position) as? CarouselViewHolder
                holder?.let {
                    it.imageView.alpha = 0f
                    it.imageView.animate().alpha(1f).setDuration(800).start()
                }
                //previousView?.animate()?.alpha(0f)?.setDuration(500)?.start()
                previousView = holder?.imageView
                onPageSelectedListener?.invoke(position)
            }

        })
    }

    fun setImages(imageUrls: List<HomeBannerAtvDto>) {
        viewPager.offscreenPageLimit = imageUrls.size
        imageList = imageUrls
        viewPager.adapter = CarouselAdapter(imageList)
        viewPager.setCurrentItem(0, false)
    }

    fun startAutoScroll() {
        stopAutoScroll()
        autoScrollJob = CoroutineScope(Dispatchers.Main).launch {
            while (isActive && imageList.size > 1) {
                delay(autoScrollInterval)
                val nextIndex =
                    if (viewPager.currentItem + 1 >= imageList.size) 0 else viewPager.currentItem + 1
                viewPager.setCurrentItem(nextIndex, false)
            }
        }
    }

    fun stopAutoScroll() {
        autoScrollJob?.cancel()
        autoScrollJob = null
    }

    // 手动控制API
    fun nextPage(smoothScroll: Boolean = false) {
        val nextIndex =
            if (viewPager.currentItem + 1 >= imageList.size) 0 else viewPager.currentItem + 1
        viewPager.setCurrentItem(nextIndex, smoothScroll)
        resetAutoScrollTimer()
    }

    fun previousPage(smoothScroll: Boolean = false) {
        val prevIndex =
            if (viewPager.currentItem - 1 < 0) imageList.size - 1 else viewPager.currentItem - 1
        viewPager.setCurrentItem(prevIndex, smoothScroll)
        resetAutoScrollTimer()
    }

    private fun resetAutoScrollTimer() {
        stopAutoScroll()
        startAutoScroll()
    }

    var adJob: Job ?=null
    private inner class CarouselAdapter(private val items: List<HomeBannerAtvDto>) :
        RecyclerView.Adapter<CarouselViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarouselViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_carousel_layout, parent, false)
            return CarouselViewHolder(view)
        }

        override fun onBindViewHolder(holder: CarouselViewHolder, position: Int) {
            val item = items[position]
            with(holder) {
                // 重置控件状态
               // imageView.visibility = View.GONE
                adContainer.visibility = View.GONE
                imageView.alpha = 0f // 初始 alpha 0

                if (item.isAd) {
                    // 广告模式

                    // 假设 AdManager 是 SDK 提供的广告管理类

                   // imageView.setImageResource(R.drawable.icon_sraf)
                    Glide.with(imageView.context)
                        .load(item.app_img ?: item.bannerRes)
                        .into(imageView)

                    adJob?.cancel() // 取消之前的任务
                    adJob = (currentActivity as FragmentActivity).lifecycleScope.launch {
                        while (isActive) {
                            delay(5000) // 初始或完成后的 10 秒间隔
                            suspendCancellableCoroutine<Unit> { continuation ->

                                AdManagerImpl.showAd(
                                    adContainer,
                                    adStart = {
                                        adContainer.isVisible = true
                                        imageView.isVisible = false
                                    },
                                    adError = {
                                        adContainer.isVisible = false
                                        imageView.isVisible = true
                                        continuation.resume(Unit)
                                              },
                                    adComplete = {
                                        adContainer.isVisible = false
                                        imageView.isVisible = true
                                        continuation.resume(Unit)
                                    }
                                )

                            }
                        }
                    }



                } else {
                    // 普通图片模式
                    imageView.visibility = View.VISIBLE
                    Glide.with(imageView.context)
                        .load(item.app_img ?: item.bannerRes)
                        .into(imageView)
                }
            }
        }

        override fun getItemCount(): Int = items.size
    }

    class CarouselViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.carousel_image)
        val adContainer: FrameLayout = itemView.findViewById(R.id.ad_container)
    }

    override fun requestFocus(direction: Int, previouslyFocusedRect: Rect?): Boolean {
        return false
    }

    override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        if (gainFocus) {
            clearFocus()
        }
    }
}
